import os
import random
import math
import time

import cv2 as cv
import numpy as np
import multiprocessing

width = 1024
height = 1280


def show_img_imshow(img_):
    cv.namedWindow("img")
    cv.imshow("img", img_)
    cv.waitKey(0)


def create_img_by_img(filepath):
    # 读取原始图像并转换为灰度图像
    image = cv.imread(str(filepath), cv.IMREAD_GRAYSCALE)
    # 获取原始图像的灰度值分布直方图
    hist = cv.calcHist([image], [0], None, [256], [0, 256])
    # 计算累积直方图
    cdf = hist.cumsum()
    # 归一化累积直方图
    cdf_normalized = cdf / cdf.max()
    # 生成随机数列
    random_values = np.random.rand(image.shape[0] * image.shape[1])
    # 根据灰度值分布对随机数列进行排序
    sorted_values = np.interp(random_values, cdf_normalized, np.arange(0, 256))
    # 将排序后的值重塑为与原始图像相同大小的矩阵
    sorted_image = np.reshape(sorted_values, image.shape).astype(np.uint8)
    return sorted_image


def get_bandian():
    bandian_image = cv.imread("/disk/data4T/yolov7_test/yolo_v7/realData/2305251/circle+circlering/1.bmp",
                              cv.IMREAD_GRAYSCALE)
    minx, miny = 400, 651
    maxx, maxy = 499, 725
    cropped_bandian_image = bandian_image[miny:maxy, minx:maxx]
    blurred = add_mean_filter(cropped_bandian_image, kernel_size=3)
    return blurred


# def random_creator_bandian():


def add_bandian_to_originImg(originImg, _res_path):
    bandian_img = get_bandian()
    orH, orW = originImg.shape[:2]
    banH, banW = bandian_img.shape[:2]
    x = random.randint(0, orW - banW)
    y = random.randint(0, orH - banH)
    x_end = x + banW
    y_end = y + banH
    centerx = ((x_end - x) / 2 + x) / orH
    centery = ((y_end - y) / 2 + y) / orW
    dx4 = (2 * (x_end - x)) / height
    dy4 = (2 * (y_end - y)) / width
    originImg[y:y_end, x:x_end] = bandian_img
    _res_path.write("3" + ' ')
    _res_path.write(str(centerx) + ' ')
    _res_path.write(str(centery) + ' ')
    _res_path.write(str(dx4) + ' ')
    _res_path.write(str(dy4) + ' ' + '\n')
    # cv.rectangle(originImg, (x, y), (x_end, y_end), 0, 3)
    return originImg


# 添加椒盐噪点
def add_salt_and_pepper_noise(image, noise_ratio):
    noisy_pixels = int(noise_ratio * image.size)
    # salt_coords = [np.random.randint(0, d - 1, noisy_pixels) for d in image.shape]
    # image[salt_coords] = 255
    # pepper_coords = [np.random.randint(0, d - 1, noisy_pixels) for d in image.shape]
    # image[pepper_coords] = 0
    for _ in range(noisy_pixels):
        row = np.random.randint(0, image.shape[0])
        col = np.random.randint(0, image.shape[1])
        if np.random.rand() < 0.5:
            image[row, col] = 0  # 设置为黑色
        else:
            image[row, col] = 255  # 设置为白色c


# 添加高斯噪点
def add_guassian_noise(img, mean, stddev):
    noise = np.random.normal(mean, stddev, img.shape).astype(np.uint8)
    noisy_image = cv.add(img, noise)
    return np.clip(noisy_image, 0, 255).astype(np.uint8)


# 添加斑点噪声
def add_speckle_noise(image_, std_dev):
    h, w = image_.shape
    noise = np.random.randn(h, w) * std_dev
    noisy_image = image_ + image_ * noise
    noisy_image = np.clip(noisy_image, 0, 255).astype(np.uint8)
    return noisy_image


# 添加光影
def add_light_and_shadow(image_, brightness, contrast):
    img_float = image_.astype(np.float32)
    brightened_image = cv.add(img_float, brightness)
    adjusted_image = cv.multiply(brightened_image, contrast)
    shadowed_image = (adjusted_image * 255).astype(np.uint8)
    return shadowed_image


# 生成一张随机的模糊图片
def create_img_random(width, height):
    # img_ = np.zeros((width, height), dtype=np.uint8)
    random_array = np.random.randint(0, 256, size=(width, height), dtype=np.uint8)
    new_image = np.where(random_array < 128, 0, random_array)
    # mat_img = cv.cvtColor(img, cv.COLOR_BGR2GRAY)
    # it = np.nditer(img_, flags=['multi_index'], op_flags=['readwrite'])
    # while not it.finished:
    #     # 生成随机灰度值
    #     gray_value = np.random.randint(0, 256)
    #     # 赋值给图像的对应像素
    #     it[0] = gray_value
    #     # img[x, y] = gray_value
    #     it.iternext()

    return new_image


# 均值滤波器
def add_mean_filter(image, kernel_size):
    kernel = np.ones((kernel_size, kernel_size), dtype=np.uint8) / (kernel_size * kernel_size)
    filtered_image = cv.filter2D(image, -1, kernel)
    return filtered_image


# 中值滤波器
def add_median_filter(image, kernel_size):
    filter_image = cv.medianBlur(image, kernel_size)
    return filter_image


if __name__ == '__main__':
    img = 255 * np.zeros((width, height), dtype=np.uint8)
    speckle_std_dev = 0.7
    speckle_img = add_speckle_noise(img, speckle_std_dev)
    cv.imshow("image", img)
    cv.waitKey(0)

    # image = cv.imread("D:/ring_circles/1/1.bmp", cv.IMREAD_GRAYSCALE)
    #
    # brightness_ = 0.2
    # contrast_ = 1.5
    # res_img = add_light_and_shadow(image, brightness_, contrast_)
    # cv.imshow("res", res_img)
    # cv.waitKey(0)
